<template>
  <div class="box">
    <div class="login_title">
      <!-- <el-image src="../assets/Vue.png" fit="cover"></el-image> -->
      <p>在线考试系统</p>
    </div>
    <el-form :model="form" ref="formRuleRef" :rules="formRule">
      <el-form-item label="手机号" prop="phone">
        <el-input placeholder="请输入手机号" v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密&nbsp&nbsp&nbsp码" prop="password">
        <el-input placeholder="请输入密码" show-password v-model="form.password"></el-input>
      </el-form-item>
    </el-form>
    <div class="bottom_options">
      <div style="flex-grow: 1"></div>
      <el-button type="primary" class="btn_login" @click="click_login(formRuleRef)">登录
      </el-button>
      <el-button class="btn_find_password" link style="margin: 0.5em 0 0 0">找回密码
      </el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { reactive, ref} from "vue";
import {UserStore} from "../../store/store";
import {UserRequest} from "../../request/MyRequset"
import router from "../../router/router";
import {User} from "../../types/mytypes";
import {FormInstance, FormRules} from "element-plus";
let form = reactive({
  phone:"",
  password:""
})
let formRuleRef = ref<FormInstance>()
let formRule = reactive<FormRules>({
  phone:[
    {required: true, message: "不能为空"},
  ],
  password:[
    {required: true, message: "不能为空"},
  ],
})
const emit = defineEmits(["dialog"])
const click_login = async(formEl: FormInstance | undefined)=>{
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid)return;
    let res = await UserRequest.userLogin(form.phone, form.password);
    if (res.suc) {
      let userData: User = res.data
      //登录成功时，利用localStorage存储用户数据
      UserStore.setUser(userData);
      emit("dialog", {
        show: true, msg: `欢迎您，${userData.name}，点击确定跳转到首页`, func: () => {
          router.push({name: 'index'})
        }
      });
    } else {
      //登录失败时弹窗提示用户
      emit("dialog", {
        show: true, msg: "登录失败，请检查手机号或密码！", func: () => {
        }
      });
    }
  })
}
</script>

<style scoped lang="scss">
.box {
  max-width: 30vw;
  width: 25vw;
  height: 25vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .login_title > p {
    height: auto;
    font-size: 2em;
    font-weight: bold;
  }

  .login_input {
    width: 50%;
  }

  .margin_top {
    margin-top: 1em;
  }

  .bottom_options {
    margin-top: 1em;
    width: 60%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    .btn_login {
      margin: 0;
      width: 40%;
      flex-grow: 1;
    }

    .btn_find_password {
      margin: 0;
      flex-grow: 1;
    }
  }
}
</style>
